<?php

namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use yii\web\UploadedFile;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\AllEX;
use common\models\Group;
use common\models\Config;
use yii\helpers\ArrayHelper;

/**
 * Chart controller
 */
class ChartController extends Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        if (Config::getLicense()['sensorNowCount'] == 0) {
            $rules = [];
        } else {
            $rules = [
                [
                    'actions' => [''],
                    'allow' => true,
                    'roles' => ['?'],
                ],
                [
                    'actions' => ['index', 'group'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
                [
                    'actions' => [],
                    'allow' => true,
                    'roles' => ['admin'],
                ],
            ];
        }
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['index', 'group'],
                'rules' => $rules,
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                // 'logout' => ['post'],
                // 'test' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions() {
        $this->isAPI();
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public $enableCsrfValidation = false;

    private function isAPI() {
        $headers = Yii::$app->request->headers;
        if (stristr($headers['accept'], 'application/json') !== false) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        } else {
            Yii::$app->response->format = \yii\web\Response::FORMAT_XML;
        }
    }

    public function actionIndex() {
        $data['status'] = 'success';
        $data['Sensor'] = $this->sensor();
        $data['SensorTop'] = $this->sensorTop();
        $data['File'] = $this->file();
        $data['FileTop'] = $this->fileTop();
        $data['OSData'] = $this->OSData();

        return $data;
    }

    public function sensor() {
        $time = mktime(0, 0, 0, date("m"), date("d"), date("Y")) - (86400 * 13);
        $data = AllEX::find()->select(['SensorID', 'created_at'])->where(['>', 'created_at', $time])->all();
        $data = ArrayHelper::toArray($data);
        return $data;
    }

    public function sensorTop() {
        $time = mktime(0, 0, 0, date("m"), date("d"), date("Y")) - (86400 * 89);
        $sql = 'SELECT SensorID,ComputerName, COUNT(1) AS count 
                FROM AllEX 
                WHERE created_at > ' . $time . '
                GROUP BY SensorID 
                ORDER BY count DESC 
                LIMIT 10';
        $data = Yii::$app->db->createCommand($sql)->query();
        return $data;
    }

    public function file() {
        $time = mktime(0, 0, 0, date("m"), date("d"), date("Y")) - (86400 * 13);
        $data = AllEX::find()->select(['id', 'created_at'])->where(['>', 'created_at', $time])->andWhere(['Type' => 'File'])->all();
        $data = ArrayHelper::toArray($data);
        return $data;
    }

    public function fileTop() {
        $time = mktime(0, 0, 0, date("m"), date("d"), date("Y")) - (86400 * 89);
        $sql = 'SELECT id,Label, COUNT(1) AS count 
                FROM AllEX
                WHERE Type = "File"
                AND created_at > ' . $time . '
                GROUP BY MD5 
                ORDER BY count DESC
                LIMIT 10';
        $data = Yii::$app->db->createCommand($sql)->query();
        return $data;
    }

    public function OSData() {
        $time = mktime(0, 0, 0, date("m"), date("d"), date("Y")) - (86400 * 89);
        $sql = 'SELECT "all" AS type,OSTypeShort, COUNT(SensorID) AS count FROM sensor GROUP BY OSTypeShort
                UNION
                SELECT "alert" AS type,OSTypeShort, COUNT(DISTINCT SensorID) FROM AllEX WHERE created_at > ' . $time . ' GROUP BY OSTypeShort';
        $data = Yii::$app->db->createCommand($sql)->query();
        return $data;
    }

    public function actionGroup() {
        if (!Yii::$app->request->isPost) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Not post request';
            return $data;
        }
        $groupIDList = json_decode(Yii::$app->request->getRawBody(), true);
        $groupList = Group::find()->where(['id' => $groupIDList])->all();
        $data['GroupData'] = ['textList' => [], 'countAlert' => [], 'countUnalert' => []];
        $time = mktime(0, 0, 0, date("m"), date("d"), date("Y")) - (86400 * 89);
        foreach ($groupList as $key => $group) {
            $SensorIDList = $group->getSensorIDList();
            $data['GroupData']['textList'][] = $group->text;
            $countAlert = (int) AllEX::find()->select(['SensorID'])->distinct()->where(['SensorID' => $SensorIDList])->andWhere(['>', 'created_at', $time])->count();
            $countUnalert = count($SensorIDList) - $countAlert;
            $data['GroupData']['countAlert'][] = $countAlert;
            $data['GroupData']['countUnalert'][] = $countUnalert;
        }
        $data['status'] = 'success';
        return $data;
    }

}
